<?php
require_once dirname(dirname( __FILE__ ))."/include/functions.php";

// language files
$langmanpath = XOOPS_TRUST_PATH.'/libs/altsys/class/D3LanguageManager.class.php' ;
if( ! file_exists( $langmanpath ) ) return ;
require_once( $langmanpath ) ;



//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function flatdata_embed_display($fd_dir ,$embed_dir, $item_field, $item_id, $params)
{
	global $xoopsUser , $xoopsConfig ;// $xoopsDB ,

	$mydirname = preg_replace( '/[^a-zA-Z0-9_-]/' , '' , $fd_dir ) ;
	read_language_file($mydirname);
	require dirname(dirname( __FILE__ ))."/main/header.php";
	//----------------------------------------------------------------------

	// check the flatdata exists and isactive
	if( ! is_object( $xoopsModule ) || ! $xoopsModule->getVar('isactive') ) {
		return ;
	}

	// check permission of "module_read" of flatdata
	$moduleperm_handler =& xoops_gethandler( 'groupperm' ) ;
	$groups = is_object( $xoopsUser ) ? $xoopsUser->getGroups() : array( XOOPS_GROUP_ANONYMOUS ) ;
	if( ! $moduleperm_handler->checkRight( 'module_read' , $xoopsModule->getVar('mid') , $groups ) ) {
		return ;
	}

	//permission check
	if( !$isadmin ){
		if( in_array($embed_dir,$sp_embed_dir) ){
			if( $embed_dispperm==1 ){
				if( $item_id!=$uid ) return ;
			}
		}
	}

	//----------------------------------------------------------------------
	$fidarr = $fields->getFidArray();//'list'
	$use_count = FALSE;

	if (isset($params['preview']) && $params['preview'] == 1) {
		$postdata = $flatdata->getPOSTDATA($fidarr);
		$data[0]['did'] = isset($_POST['flatdata_did']) ? intval($_POST['flatdata_did']) : 0 ;
		$data[0]['data'] = $flatdata->splitData($postdata,$fidarr);
	} else {
		$flatdata->setEmbedWhere("[$embed_dir][$item_field][$item_id]%");
		$data = $flatdata->getDatas( $fidarr , 0 ) ;

		if( $params['count']==1 ){
			$use_count = TRUE;
		}else{
			if (!(isset($params['through']) && $params['through'] == 1)) {
				if( count($data)<1 ) return ;

				//field data empty check
				$counter = 0;
				for ($i = 0; $i < count($fidarr); $i++) {
					$fid = $fidarr[$i];
					if (! empty($data[0]['data'][$fid])) {
						$counter++;
						break;
					}
				}
				if ($counter == 0) return;
			}
		}
	}

	$allfields = $fields->getAllFields();
	if (count($allfields) < 1) return;
	$switch = isset($params['switch']) ? intval($params['switch']): 0; 
	//----------------------------------------------------------------------
	require_once XOOPS_ROOT_PATH.'/class/template.php';
	$tpl = new XoopsTpl();
	$tpl->assign('switch', $switch);
	$tpl->assign('fields', $allfields);
	$tpl->assign('data', $data);
	$tpl->assign('count', intval(count(@$data)));
	$tpl->assign('use_count',$use_count);
	$tpl->assign($basic_assign);
	$tpl->display('db:'.$mydirname."_embed_display.html");
	//----------------------------------------------------------------------
}



//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function flatdata_embed_form($fd_dir, $embed_dir, $item_field, $item_id, $preload=0, $params)
{
	global $xoopsUser, $xoopsConfig ;

	$mydirname = preg_replace( '/[^a-zA-Z0-9_-]/' , '' , $fd_dir ) ;
	read_language_file($mydirname);
	require dirname(dirname( __FILE__ ))."/main/header.php";
	//----------------------------------------------------------------------
	$allfields = $fields->getAllFields();
	if ( count($allfields)<1 ) return ;

	$pathArray = parse_url( xoops_getenv('REQUEST_URI') ) ;
	$querystring = empty($pathArray['query']) ? '' : '?'.$pathArray['query'] ;
	if (basename($pathArray['path']) == $embed_dir) {
		$filequery = $querystring ;
	} else {
		$filequery = basename($pathArray['path']). $querystring ;
	}
	$filequery = preg_replace('/[^a-zA-Z0-9\.\?=&_-]/', '', $filequery);

	//get data 
	$fidarr = $fields->getFidArray();//'list'
	$flatdata->setEmbedWhere("[$embed_dir][$item_field][$item_id]%");
	$data = $flatdata->getDatas( $fidarr );

	//OPTION(post=multi) : Two or more data is possible to embed in one data of other modules. 
	$post_multi = (isset($params['post']) && $params['post']=='multi') ? TRUE: FALSE;

	//permission check
	if (! $isadmin) {
		if ( $embed_dir=='register.php' ) {
			if( count($data)>0 ){
				if( $item_id!=$uid || $uid==0 ) return ;
			}
		} else if ( $embed_dir=='edituser.php' || $embed_dir=='userinfo.php' ){
			if( $item_id!=$uid || $uid==0 ) return ;
		} else {
			if( count($data)>0 && ! $post_multi ){
				if( ! $editperm ) return ;
				if( $data[0]['uid']!=$uid ) return ;
			}else{
				if( ! $postperm ) return ;
			}
		}
	}

	if (isset($_SESSION['flatdata_confirm'])) {
		$data[0] = flatdata_getDataForConfirm($fidarr,$mydirname) ;
	}

	//check form tag on/off
	if (defined('XOOPS_CUBE_LEGACY')) {
		$preload_file = XOOPS_ROOT_PATH ."/preload/FlatdataEmbeddataInsert.class.php" ;
		$formtag = ( ($embed_dir=='edituser.php' || $embed_dir=='register.php' || $preload==1 ) && file_exists($preload_file) ) ? FALSE : TRUE;
	} else {
		$formtag = ($preload == 1) ? FALSE: TRUE;
	}

	$switch = isset($params['switch']) ? intval($params['switch']): 0; 
	//---------------------------------------------------------------
	require_once XOOPS_ROOT_PATH.'/class/template.php';
	$tpl = new XoopsTpl();
	$tpl->assign('switch', $switch);
	$tpl->assign($basic_assign);
	$tpl->assign(array(
			'data'       => $data,
			'fields'     => $allfields,
			'gticket'    => $GLOBALS['xoopsGTicket']->getTicketHtml(__LINE__, 1800, 'flatdata_embed_submit'),
			'formtag'    => $formtag,
			'post_multi' => $post_multi,
		)
	);
	$tpl->assign('basedata',array(
			'fd_dir'     => $mydirname ,
			'embed_dir'  => htmlspecialchars($embed_dir, ENT_QUOTES, _CHARSET) ,
			'item_field' => htmlspecialchars($item_field, ENT_QUOTES, _CHARSET) ,
			'item_id'    => $item_id ,
			'filequery'  => $filequery ,
		)
	);
	$tpl->display('db:'. $mydirname .'_embed_form.html');
	//---------------------------------------------------------------
}


//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function flatdata_embed_post($fd_dir ,$embed_dir, $item_field, $item_id, $mode)
{
	global $xoopsUser, $xoopsConfig;
	$myts = & MyTextSanitizer::getInstance() ;

	$mydirname = preg_replace('/[^a-zA-Z0-9_-]/', '', $fd_dir);
	read_language_file($mydirname);
	require dirname(dirname( __FILE__ )) ."/main/header.php";
	//----------------------------------------------------------------------
	$embed_dir = isset($_POST['flatdata_embed_dir']) ? $myts->stripSlashesGPC($_POST['flatdata_embed_dir']): '';
	$embed_dir = preg_replace('/[^a-zA-Z0-9_-]/', '', $embed_dir);

	$fidarr = $fields->getFidArray();
	$did = isset($_POST['flatdata_did']) ? intval($_POST['flatdata_did']): 0;
	if (empty($_POST['flatdata_item_id'])) $_POST['flatdata_item_id'] = $item_id;

	//permission check
	if (! $isadmin) {
		if (in_array($embed_dir, $sp_embed_dir)) {
			if ($_POST['flatdata_item_id'] != $uid || $uid == 0) {
				return _MD_FD_EMBED_NOPERM;
			}
		} else if ($mode == 'insert') {
			if (! $postperm) {
				return _MD_FD_EMBED_NOPERM;
			}
		} else if ($mode == 'update') {
			$data = $flatdata->getData($did, $fidarr);
			if (! $editperm || $data['uid'] != $uid) {
				return _MD_FD_EMBED_NOPERM;
			}
		} else if ($mode == 'delete') {
			$data = $flatdata->getData( $did , $fidarr );
			if (! $delperm || $data['uid'] != $uid) {
				return _MD_FD_EMBED_NOPERM;
			}
		} else {
			return _MD_FD_EMBED_NOPERM;
		}
	}

	//----------------------------------------------------------------------
	if ($mode == 'delete') {
		$flatdata->delete($did);
		return '';
	} else if ($mode == 'insert' || $mode == 'update') {
		if (! $flatdata->embed_preCheck($fidarr)) {
			return _MD_FD_NO_DATA;
		}

		if (empty($did)) {
			$flatdata->embedData() ;
			$flatdata->insert($fidarr);
		} else {
			$flatdata->update($did, $fidarr);
		}
		return '';
	} else {
		return _MD_FD_EMBED_NOPERM;
	}
}


//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
function flatdata_getDataForConfirm($fidarr,$mydirname)
{
	$post = unserialize($_SESSION['flatdata_confirm']) ;
	$data = array() ;
	for( $i=0; $i<count($fidarr); $i++ ){
		$fid = $fidarr[$i] ;
		$f_name = $mydirname ."_field". $fid ;
		$f = "field". $fid ;
		$temp = isset($post[$f_name]) ? flatdata_receiveData($post[$f_name]) : "" ;
		if( empty($temp) ){
			$temp = isset($post[$f]) ? flatdata_receiveData($post[$f]) : "" ;
		}
		$data['data'][$fid] = htmlspecialchars($temp, ENT_QUOTES, _CHARSET) ;
	}
	$data['cat_id'] = intval($post['cat_id']) ;
	unset($_SESSION['flatdata_confirm']) ;
	return $data ;
}

function flatdata_receiveData( $data )
{
	$myts = & MyTextSanitizer::getInstance() ;
	$data = $myts->stripSlashesGPC($data) ;
	$data = preg_replace( 
		array("/\[field/si","/\[\/field/si") , 
		array("[ field","[ /field") ,
		$data 
	);
	return $data ;
}

function read_language_file($fd_dir)
{
	$langman =& D3LanguageManager::getInstance() ;
	$fd_trust_dirname = basename(dirname(dirname(__FILE__))) ;
	$langman->read('main.php', $fd_dir, $fd_trust_dirname) ;
}

